package com.xxxx.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxxx.server.Utils.DateUtils;
import com.xxxx.server.mapper.IvaccineMapper;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.Ivaccine;
import com.xxxx.server.pojo.RespBean;
import com.xxxx.server.pojo.RespPageBean;
import com.xxxx.server.service.IIvaccineService;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 辅导员疫苗登记表 前端控制器
 * </p>
 *
 * @author zhoubin
 * @since 2022-06-01
 */
@RestController
@RequestMapping("/vac/ins/")
public class IvaccineController {
    @Autowired
    private IIvaccineService iIvaccineService;
    @Autowired
    private IvaccineMapper ivaccineMapper;

    @ApiOperation(value = "获取所有辅导员疫苗信息（学校）")
    @GetMapping("/getall")
    public List<Ivaccine> getAllIvaccines(){
        return iIvaccineService.list();
    }

//    @ApiOperation(value = "根据学院查询辅导员疫苗信息（学院）")
//    @GetMapping("/getbycolege")
//    public List<Ivaccine> getByColegeIdIvaccines(){
//        return iIvaccineService.getByColegeIdIvaccines();
//    }

    @ApiOperation(value = "获取自己的疫苗信息（辅导员）")
    @GetMapping("/getone")
    public Ivaccine getOneIvaccines(){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("IVid",((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
        queryWrapper.eq("enable",1);
        return iIvaccineService.getOne(queryWrapper);
    }

    @ApiOperation(value = "添加辅导员疫苗信息（用户添加）")
    @PostMapping("/post")
    public RespBean addIvaccine(@RequestBody Ivaccine ivaccine){

        QueryWrapper<Ivaccine> wrapper = new QueryWrapper<>();
        wrapper.eq("IVid",((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
        wrapper.eq("enable",1);
        List<Ivaccine> arry = ivaccineMapper.selectList(wrapper);
        for (int i = 0; i < arry.size(); i++) {
            arry.get(i).setEnable(0);
        }
        iIvaccineService.updateBatchById(arry);

        ivaccine.setIVid(((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
        ivaccine.setIVdate(LocalDateTime.now());
        ivaccine.setEnable(1);
        if (iIvaccineService.save(ivaccine)){
            return RespBean.success("添加成功！");
        }
        return RespBean.error("添加失败!");
    }

    @ApiOperation(value = "更新辅导员疫苗信息（用户更新）")
    @PutMapping("/update")
    public RespBean updateIvaccine(@RequestBody Ivaccine ivaccine){
        ivaccine.setIVid(((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
        ivaccine.setEnable(1);
        if (iIvaccineService.updateById(ivaccine)){
            return RespBean.success("更新成功！");
        }
        return RespBean.error("更新失败！");
    }

    @ApiOperation(value = "查询所有的辅导员疫苗（分页）")
    @GetMapping("/getPageIvaccine/")
    public RespPageBean getInVaccine(@RequestParam(defaultValue = "1") Integer currentPage ,
                                     @RequestParam(defaultValue = "10")Integer size,
                                     Ivaccine ivaccine,
                                     String[] beginDateScope,
                                     String collegename){
        Admin admin = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int type=admin.getRoles().get(0).getId();
        int collegeid;
        if(admin.getCollegeid()!=null){
            collegeid = admin.getCollegeid();
        }else{
            collegeid=0;
        }
        return iIvaccineService.getInvaccineByPage(currentPage,size,ivaccine,beginDateScope,type,collegename,collegeid);
    }

    @ApiOperation(value = "登录的辅导员疫苗上报是否有效（用户查询）")
    @PutMapping("/isEffective")
    public int isEffectiveIvaccine() throws ParseException {
        QueryWrapper<Ivaccine> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("enable",1);
        queryWrapper.eq("IVid",((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
        Ivaccine ivaccine = iIvaccineService.getOne(queryWrapper);
        if(ivaccine == null)
            return 0;

        SimpleDateFormat ft = new SimpleDateFormat("MM-dd hh:mm:ss");
        String nowtime = LocalDateTime.now().toString();

        String startMonth = nowtime.substring(5,7);
        int end = Integer.parseInt (startMonth)+1;

        String endMonth = String.valueOf(end);
        Date startTime = ft.parse(startMonth+"-01 00:00:00");
        Date endTime = ft.parse(endMonth+"-01 00:00:00");

        String time = ivaccine.getIVdate().toString();
        time = time.substring(5,10) + " " + time.substring(11,19);
        Date testTime = ft.parse(time);

        boolean effectiveDate = DateUtils.isEffectiveDate(testTime, startTime, endTime);
        if (effectiveDate) {
            return 1;
        }else {
            return 0;
        }
    }


    @ApiOperation(value = "导出辅导员疫苗接种数据")
    @GetMapping(value = "/export",produces = "application/octet-stream")
    public void exportIvaccine(HttpServletResponse response,
                               Ivaccine ivaccine,
                               String[] beginDateScope,
                               String collegename){
        Admin admin = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int type=admin.getRoles().get(0).getId();
        int collegeid;
        if(admin.getCollegeid()!=null){
            collegeid = admin.getCollegeid();
        }else{
            collegeid=0;
        }
        List<Ivaccine> list = iIvaccineService.getInvaccineSeachList(ivaccine,beginDateScope,type,collegename,collegeid);
        ExportParams params = new ExportParams("辅导员疫苗接种情况表","辅导员疫苗接种情况表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Ivaccine.class, list);
        ServletOutputStream out = null;
        try {
            //流形式
            response.setHeader("content-type","application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("辅导员疫苗接种情况表.xls","UTF-8"));
            out = response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null!=out){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
